package com.hotchpotch.activity;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.TextView;

import com.hotchpotch.R;
import com.hotchpotch.bean.CitiesBean;
import com.hotchpotch.util.JsonUtil;
import com.hotchpotch.util.Utils;
import com.hotchpotch.bean.AddressDtailsEntity;
import com.hotchpotch.bean.AddressModel;
import com.hotchpotch.util.HanziToPinyin;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/6/8 0008.
 */

public class TwoActivity extends AppCompatActivity {
    private List<AddressDtailsEntity> addrModels = new ArrayList<>();
    private TextView textView;
    private String text = "";
    private List<AddressDtailsEntity> cityList = new ArrayList<>();
    private List<CitiesBean> citiesBeenList = new ArrayList<>();
    private String[] mSections = {"A", "B", "C", "D", "E", "F",
            "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
            "T", "U", "V", "W", "X", "Y", "Z"};

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    textView.setText(text);
                    break;
                case 1:
                    String str = JsonUtil.toJson(citiesBeenList);
//                    writeTxtToFile(str, filePath, fileName);
                    saveFile(str);
                    textView.setText("转化完成，已写入本地txt文本");
                    break;
            }
        }
    };

    public static void saveFile(String str) {
        String filePath = null;
        boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (hasSDCard) { // SD卡根目录的hello.text
            filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "city.txt";
        } else  // 系统下载缓存根目录的hello.text
            filePath = Environment.getDownloadCacheDirectory().toString() + File.separator + "city.txt";

        try {
            File file = new File(filePath);
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            FileOutputStream outStream = new FileOutputStream(file);
            outStream.write(str.getBytes());
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
        initView();
        initData();
    }

    private void initView() {
        textView = (TextView) findViewById(R.id.textview);
    }

    private void initData() {
        String address = Utils.readAssert(this, "region.txt");
        AddressModel model = JsonUtil.parseJson(address, AddressModel.class);
        if (model != null) {
            addrModels.addAll(model.RECORDS);
            text = "获取到原始数据";
            handler.sendEmptyMessage(0);
        }

        getCityList();
        setLetter();
        getList();
    }

    private void getCityList() {
        for (int i = 0; i < addrModels.size(); i++) {//市级集合
            if (addrModels.get(i).region_type == 2) {
                AddressDtailsEntity areaBean = new AddressDtailsEntity();
                areaBean.region_id = addrModels.get(i).region_id;
                areaBean.parent_id = addrModels.get(i).parent_id;
                areaBean.region_name = addrModels.get(i).region_name;
                areaBean.region_type = addrModels.get(i).region_type;
                areaBean.agency_id = addrModels.get(i).agency_id;
                cityList.add(areaBean);
            }
        }
        text = "得到城市的集合";
        handler.sendEmptyMessage(0);
    }

    private void setLetter() {
        for (int i = 0; i < mSections.length; i++) {
            CitiesBean bean = new CitiesBean();
            bean.letter = mSections[i];
            citiesBeenList.add(bean);
        }
        text = "字母添加完成";
        handler.sendEmptyMessageDelayed(0, 3000);
    }

    private void getList() {
        text = "开始添加城市数据到对应字母下";
        handler.sendEmptyMessage(0);
        for (int i = 0; i < citiesBeenList.size(); i++) {
            for (int j = 0; j < cityList.size(); j++) {
                if (citiesBeenList.get(i).letter.equals(getLetter(cityList.get(j).region_name))) {
                    citiesBeenList.get(i).cityList.add(cityList.get(j));
                }
            }
        }
        text = "完成数据编辑";
        handler.sendEmptyMessage(0);
        handler.sendEmptyMessageDelayed(1, 3000);
    }

    /**
     * 根据字符串获取当前首字母
     *
     * @param name
     * @return
     */
    static String getLetter(String name) {
        String DefaultLetter = "#";
        if (TextUtils.isEmpty(name)) {
            return DefaultLetter;
        }
        char char0 = name.toLowerCase().charAt(0);
        if (Character.isDigit(char0)) {
            return DefaultLetter;
        }
        ArrayList<HanziToPinyin.Token> l = HanziToPinyin.getInstance().get(name.substring(0, 1));
        if (l != null && l.size() > 0 && l.get(0).target.length() > 0) {
            HanziToPinyin.Token token = l.get(0);
            // toLowerCase()返回小写， toUpperCase()返回大写
            String letter = token.target.substring(0, 1).toUpperCase();
            char c = letter.charAt(0);
            // 这里的 'a' 和 'z' 要和letter的大小写保持一直。
            if (c < 'A' || c > 'Z') {
                return DefaultLetter;
            }
            return letter;
        }
        return DefaultLetter;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
